﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace ACompany.OrderProcessing.NHibernateRepository
{
    public static class SessionFactory
    {
        private static ISessionFactory _sessionFactory;

        private static void Init()
        {
            Configuration config = new Configuration();

            config.AddAssembly("ACompany.OrderProcessing.NHibernateRepository");
            log4net.Config.XmlConfigurator.Configure();

            //important :only use it at first run and then comment out
            //NHibernate.Tool.hbm2ddl.SchemaExport se = new SchemaExport(config);
            //se.Execute(false, true, false, false);

            config.Configure();
            _sessionFactory = config.BuildSessionFactory();
        }


/*
        public static void GenerateDatabaseSchemaFromMappings()
        {
            Configuration config = new Configuration();

            NHibernate.Tool.hbm2ddl.SchemaExport se = new SchemaExport(config);
            se.Execute(false, true, false, false);

            config.Configure();
            config.AddAssembly("ACompany.OrderProcessing.NHibernateRepository");

            _sessionFactory = config.BuildSessionFactory();
        }
*/

        public static ISessionFactory GetSessionFactory()
        {
            if (_sessionFactory == null)
            {
                Init();
            }
            return _sessionFactory;
        }

        public static ISession GetNewSession()
        {
            return GetSessionFactory().OpenSession();
        }

        public static ISession GetCurrentSession()
        {
            return GetSessionFactory().GetCurrentSession();
        }
    }
}
